package com.css.fxfzfxqh.modules.earthquakeRiskAssessmentZoningReport.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.css.fxfzfxqh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzfxqh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzfxqh.constants.R;
import com.css.fxfzfxqh.constants.YNEnum;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.BizException;
import com.css.fxfzfxqh.modules.earthquakeRiskAssessmentZoningReport.model.dto.FxqhAssessReportTemplateAddDto;
import com.css.fxfzfxqh.modules.earthquakeRiskAssessmentZoningReport.model.dto.FxqhAssessReportTemplateUpdateDto;
import com.css.fxfzfxqh.modules.earthquakeRiskAssessmentZoningReport.model.entity.FxqhAssessReportTemplate;
import com.css.fxfzfxqh.modules.earthquakeRiskAssessmentZoningReport.model.vo.FxqhAssessReportTemplateListVo;
import com.css.fxfzfxqh.modules.earthquakeRiskAssessmentZoningReport.model.vo.ReportTemplateDetailVo;
import com.css.fxfzfxqh.modules.earthquakeRiskAssessmentZoningReport.repository.FxqhAssessReportTemplateRepository;
import com.css.fxfzfxqh.util.CreateGson;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class FxqhAssessReportTemplateService {
    @Autowired
    private FxqhAssessReportTemplateRepository fxqhAssessReportTemplateRepository;
    @Autowired
    private SUserService sUserService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AttachmentInfoService attachmentInfoService;
    private static final String TEMPLATE_CODE_PREFIX = "FXMB";
    public static final String SYS_USER_INFO_KEY = "sys:details:user";
    public static final String[] templateFileSuffix = {"doc", "docx"};

    /**
     * 获取用户信息
     * <p>
     * 用户id
     * 先走缓存，缓存没有调接口，然后存储缓存，配置缓存60分钟过期
     */
    public SUser getUser(String userId) {
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        String redisKey = SYS_USER_INFO_KEY;
        ValueOperations<String, SUser> valueOperations = redisTemplate.opsForValue();
        SUser sUser = valueOperations.get(redisKey + userId);
        if (sUser != null) {
            return sUser;
        }
        String userJson = sUserService.getSUser(userId);
        if (StringUtils.isBlank(userJson)) {
            return null;
        }
        sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        valueOperations.set(redisKey + userId, sUser);
        redisTemplate.expire(redisKey + userId, 60, TimeUnit.MINUTES);
        return sUser;
    }

    public String getUsername(String userId) {
        SUser user = this.getUser(userId);
        if (user == null) {
            return null;
        }
        return user.getUserName();
    }

    public synchronized void add(FxqhAssessReportTemplateAddDto dto) throws BizException {
        Integer count = fxqhAssessReportTemplateRepository.countByCode(dto.getCode());
        AttachmentInfoEntity attach = attachmentInfoService.getAttach(dto.getFileId());
        if (attach == null) {
            throw new BizException("无效的文件id");
        }
        String suffix = FileUtil.getSuffix(attach.getAttachName());
        if (!Arrays.asList(templateFileSuffix).contains(suffix)) {
            throw new BizException("仅支持上传文件后缀为doc或docx的模板");
        }
        if (count != 0) {
            throw new BizException("报告模板编号已被其他模板占用，请刷新页面后重试");
        }
        FxqhAssessReportTemplate fxqhAssessReportTemplate = new FxqhAssessReportTemplate();
        BeanUtils.copyProperties(dto, fxqhAssessReportTemplate);
        fxqhAssessReportTemplate.setId(IdUtil.getSnowflakeNextIdStr());
        fxqhAssessReportTemplate.setDelFlag(YNEnum.N.toString());
        fxqhAssessReportTemplateRepository.insert(fxqhAssessReportTemplate);
    }

    public String buildTemplateCode() {
        String code = fxqhAssessReportTemplateRepository.getLatestTemplateCode();
        if (StringUtils.isBlank(code)) {
            code = "0";
        }
        int num = Integer.parseInt(code.replaceAll(TEMPLATE_CODE_PREFIX, "")) + 1;
        return TEMPLATE_CODE_PREFIX + (num < 100 ? (num < 10 ? "00" + num : "0" + num) : num);
    }

    public List<FxqhAssessReportTemplateListVo> list(String code, String name) {
        List<FxqhAssessReportTemplate> list = fxqhAssessReportTemplateRepository.list(code, name);
        if (list != null) {
            return list.stream().map(o -> {
                FxqhAssessReportTemplateListVo vo = new FxqhAssessReportTemplateListVo();
                SUser user = getUser(o.getCreateUser());
                BeanUtils.copyProperties(o, vo);
                if (user != null) {
                    vo.setCreateUserName(user.getUserName());
                    vo.setCreateUnit(user.getOrgName());
                }
                return vo;
            }).collect(Collectors.toList());
        }
        return null;
    }

    public void delete(String id, String uid) {
        fxqhAssessReportTemplateRepository.delete(id, uid, new Date());
    }

    public void upload(String templateId, String fileId, String uid) {
        fxqhAssessReportTemplateRepository.upload(templateId, fileId, uid, new Date());
    }

    public ReportTemplateDetailVo detail(String id) {
        FxqhAssessReportTemplate entity = fxqhAssessReportTemplateRepository.getById(id);
        if (entity == null) {
            return null;
        }
        ReportTemplateDetailVo vo = new ReportTemplateDetailVo();
        BeanUtils.copyProperties(entity, vo);
        vo.setFile(attachmentInfoService.getAttach(entity.getFileId()));
        vo.setCreateUser(getUsername(entity.getCreateUser()));
        return vo;
    }

    public void update(FxqhAssessReportTemplateUpdateDto dto, String uid) throws BizException {
        AttachmentInfoEntity attach = attachmentInfoService.getAttach(dto.getFileId());
        if (attach == null) {
            throw new BizException("无效的文件id");
        }
        String suffix = FileUtil.getSuffix(attach.getAttachName());
        if (!Arrays.asList(templateFileSuffix).contains(suffix)) {
            throw new BizException("仅支持上传文件后缀为doc或docx的模板");
        }
        FxqhAssessReportTemplate fxqhAssessReportTemplate = new FxqhAssessReportTemplate();
        BeanUtils.copyProperties(dto, fxqhAssessReportTemplate);
        fxqhAssessReportTemplate.setUpdateUser(uid);
        fxqhAssessReportTemplate.setUpdateTime(new Date());
        fxqhAssessReportTemplateRepository.update(fxqhAssessReportTemplate);
    }
}
